package com.suixingpay.demo.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * Jackson工具
 *
 * @author noisy
 */
public class JacksonUtil {
    /**
     * 通过Jackson将数据转换为JSON字符串
     *
     * @param code -1表示操作失败，1表示操作成功
     * @param msg  返回的文字信息
     * @param data 返回的数据
     * @return 转换后的JSON字符串
     */
    public static String build(int code, String msg, Object data) {
        String result = "";
        try {
            Map<String, Object> map = new HashMap<>(3);
            map.put("code",code);
            map.put("msg",msg);
            map.put("data",data);
            ObjectMapper objectMapper = new ObjectMapper()
                    .setSerializationInclusion(JsonInclude.Include.NON_NULL)
                    .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false)
                    .setDateFormat(new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"));
            result = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String build(Object data){
        return build(1,"success",data);
    }

    public static String build(int code, String msg){
        return build(code,msg,null);
    }
}
